package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.injector.methods.Insert;
import com.baomidou.mybatisplus.core.injector.methods.SelectPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.context.BaseContext;
import com.itheima.common.result.PageResult;
import com.itheima.common.result.Result;
import com.itheima.dto.CommonPageDTO;
import com.itheima.dto.UserDataListVo;
import com.itheima.dto.YddUserPageDTO;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.YddUserService;
import com.itheima.util.JwtUtil;
import com.itheima.vo.YddArticleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSONPatch.OperationType.add;

@Service
public class YddUserServiceImpl extends ServiceImpl<YddUserMapper, YddUser> implements YddUserService {
    @Autowired
    YddArticleMapper yddArticleMapper;

    @Autowired
    YddCateMapper yddCateMapper;

    @Autowired
    YddLinkMapper yddLinkMapper;

    @Autowired
    YddTagMapper yddTagMapper;

    @Autowired
    YddAdvimgMapper yddAdvimgMapper;

    @Autowired
    YddUserDataMapper yddUserDataMapper;

    /**
     * @param user
     * @return
     */
    @Override
    public Result login(YddUser user) {
        if(user.getMobile().isEmpty()){
            return Result.error("请输入正确的用户名");
        }
        if(user.getPassword().isEmpty()){
            return Result.error("请输入正确的密码");
        }
        QueryWrapper<YddUser> qw = new QueryWrapper<YddUser>();
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        qw.eq("mobile",user.getMobile());
        qw.eq("password",password);
        YddUser sysUser = getOne(qw);
        if(sysUser==null){
            return Result.error("请输入正确的用户名和密码");
        }
        String token = JwtUtil.getToken(sysUser.getId().toString());
        Map map = new HashMap();
        map.put("token",token);
        return Result.success(map);
    }

    /**
     * 获取用户数据
     *
     * @return
     */
    @Override
    public Result getUserInfo() {
        Map map = new HashMap();
        String currentId = BaseContext.getCurrentId();
        YddUser byId = getById(currentId);

        QueryWrapper<YddArticle> qw1 = new QueryWrapper();
        qw1.eq("author",byId.getUsername()).select("count(*) num");
        List<Map<String, Object>> maps = yddArticleMapper.selectMaps(qw1);
        map.put("articleNum",maps.get(0).get("num"));

        QueryWrapper<YddUserData> qw2 = new QueryWrapper();
        qw2.eq("user_id",currentId).eq("type",1).select("count(*) num");
        List<Map<String, Object>> maps1 = yddUserDataMapper.selectMaps(qw2);
        map.put("collectNum",maps1.get(0).get("num"));

        QueryWrapper<YddUserData> qw3 = new QueryWrapper();
        qw3.eq("user_id",currentId).eq("type",2).select("count(*) num");
        List<Map<String, Object>> maps2 = yddUserDataMapper.selectMaps(qw3);
        map.put("zanNum",maps2.get(0).get("num"));
        map.put("userInfo",byId);
        return Result.success(map);
    }

    /**
     * 查询我的文章
     *
     * @return
     */
    @Override
    public Result myArticle(CommonPageDTO dto) {
        String currentId = BaseContext.getCurrentId();
        Page page = new Page(dto.getPage(), dto.getLimit());
        YddUser byId = getById(currentId);
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getAuthor,byId.getUsername());
        Page page1 = yddArticleMapper.selectPage(page,lqw);
        PageResult pageResult = new PageResult();
        pageResult.setCurrenPage(page1.getCurrent());
        pageResult.setTotalPages(page1.getPages());
        pageResult.setData(page1.getRecords());
        pageResult.setPageSize(page1.getSize());
        pageResult.setCount(page1.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 查询点赞和收藏
     *
     * @param vo
     * @return
     */
    @Override
    public Result userDataList(UserDataListVo vo) {
        Page<YddUserData> page = new Page(vo.getPage(), vo.getLimit());
        String currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<YddUserData> lqw  =new LambdaQueryWrapper();
        lqw.eq(YddUserData::getUserId,currentId);
        lqw.eq(YddUserData::getType,vo.getType());
        yddUserDataMapper.selectPage(page,lqw);
        List<YddArticleVo> collect = new ArrayList<>();
                page.getRecords().forEach(s ->{
                    YddArticle yddArticle = yddArticleMapper.selectById(s.getArticleId());
                    YddCate yddCate = yddCateMapper.selectById(yddArticle.getCateid());
                    YddArticleVo yddArticleVo = new YddArticleVo();
                    BeanUtils.copyProperties(yddArticle,yddArticleVo);
                    yddArticleVo.setCatename(yddCate.getCatename());
                    collect.add(yddArticleVo);
                });
        PageResult pageResult = new PageResult();
        pageResult.setCurrenPage(page.getCurrent());
        pageResult.setTotalPages(page.getPages());
        pageResult.setData(collect);
        pageResult.setPageSize(page.getSize());
        pageResult.setCount(page.getTotal());
        Map map = new HashMap<>();
        map.put("list",pageResult);
        return Result.success(map);
    }

    /**
     * 点赞和取消点赞接口
     *
     * @param map
     * @return
     */
    @Override
    public Result userDataHandle(Map map) {
        String type = (String)map.get("type");
        String article_id = (String)map.get("article_id");
        String action = (String)map.get("action");
        String currentId = BaseContext.getCurrentId();
        YddUserData yddUserData = new YddUserData();
        yddUserData.setType(Integer.valueOf(type));
        yddUserData.setArticleId(Integer.valueOf(article_id));
        yddUserData.setUserId(Integer.valueOf(currentId));
        if(action.equals("add")){
            yddUserDataMapper.insert(yddUserData);
        }else{
            LambdaQueryWrapper<YddUserData> lqw = new LambdaQueryWrapper();
            lqw.eq(YddUserData::getType,type);
            lqw.eq(YddUserData::getArticleId,article_id);
            lqw.eq(YddUserData::getUserId,currentId);
            yddUserDataMapper.delete(lqw);
        }
        return Result.success();
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public Result delArticle(Integer id) {
        yddArticleMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 添加文章
     *
     * @param article
     * @return
     */
    @Override
    public Result addArticle(YddArticle article) {
        yddArticleMapper.insert(article);
        return Result.success();
    }

    /**
     * 修改文章
     *
     * @param user
     * @return
     */
    @Override
    public Result editArticle(YddArticle user) {
        yddArticleMapper.updateById(user);
        return Result.success();
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @Override
    public Result updateUser(YddUser user) {
        updateById(user);
        return Result.success();
    }

    /**
     * 后台用户数据分页读取
     *
     * @param dto
     * @return
     */
    @Override
    public Result userList(YddUserPageDTO dto) {
        Page page = new Page(dto.getPage(),dto.getLimit());
        LambdaQueryWrapper<YddUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(dto.getUsername()!=null,YddUser::getUsername,dto.getUsername());
        lqw.like(dto.getMoblie()!=null,YddUser::getMobile,dto.getMoblie());
        lqw.eq(dto.getSex()!=null,YddUser::getSex,dto.getSex());
        page(page,lqw);
        PageResult pageResult = new PageResult();
        pageResult.setCurrenPage(page.getCurrent());
        pageResult.setTotalPages(page.getPages());
        pageResult.setData(page.getRecords());
        pageResult.setPageSize(page.getSize());
        pageResult.setCount(page.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 数据详情
     *
     * @param id
     * @return
     */
    @Override
    public Result rowInfo(Integer id) {
        YddUser byId = getById(id);
        return Result.success(byId);
    }

    /**
     * 用户添加
     *
     * @param user
     * @return
     */
    @Override
    public Result add(YddUser user) {
        String s = DigestUtils.md5DigestAsHex(user.getUsername().getBytes());
        user.setPassword(s);
        save(user);
        return Result.success();
    }

    /**
     * 用户修改
     *
     * @param user
     * @return
     */
    @Override
    public Result yddUserUpdate(YddUser user) {
        updateById(user);
        return Result.success();
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Result del(Integer id) {
        removeById(id);
        return Result.success();
    }
}
